import base64
import pickle


def merge_cart_cookie_to_redis(request, user, response):
    # 获取cookie中的购物车数据
    cookie_cart_str = request.COOKIES.get('cart')
    # cookie中没有数据就响应结果
    if not cookie_cart_str:
        return response
    cookie_cart_dict = pickle.loads(base64.b64decode(cookie_cart_str.encode()))
    new_cart_dict = {}  # 定义一个redis对应格式的空字典
    new_cart_selected_add = []  # 保存选中的物品
    new_cart_selected_remove = []  # 保存不选中的物品
    # 同步cookie中购物车数据
    for sku_id, cookie_dict in cookie_cart_dict.items():
        new_cart_dict[sku_id] = cookie_dict['count']
        if cookie_dict['selected']:
            new_cart_selected_add.append(sku_id)
        else:
            new_cart_selected_remove.append(sku_id)
    # 将new_cart_dict写入到redis数据库
    reids_conn = get_redis_connection('carts')
    pl = reids_conn.pipeline()
    pl.hmset('cart_%s' % user.id, new_cart_dict)
    # 勾选状态的同步
    if new_cart_selected_add:
        pl.sadd('selected_%s' % user.id, *new_cart_selected_add)
    if new_cart_selected_remove:
        pl.srem('selected_%s' % user.id, *new_cart_selected_remove)
    pl.execute()
    # 清除cookie
    response.delete_cookie('cart')
    return response